from __future__ import print_function
import time
import os


ALBUM= 'albumData2.txt'
ARTIST= 'artistData2.txt'
GENRE= 'genreData2.txt'
TRAIN= 'trainIdx2.txt'
CLASSIFIED= 'Data/train_Classified.txt'
TEST_1 = 'Data/test_raw_score.txt'
TEST= 'testTrack_hierarchy.txt'
USER_LIST = 'Data/test_UserList.txt'
USER_MEAN = 'Data/train_Mean.txt'


class_lib = {}

with open(ALBUM) as f:
	for line in f:
		temp = line.strip("\n").split("|")
		class_lib[temp[0]] = 2

with open(ARTIST) as f:
	for line in f:
		class_lib[line.strip("\n")] = 3

with open(GENRE) as f:
	for line in f:
		class_lib[line.strip("\n")] = 4


with open(CLASSIFIED,'w') as trainMod:
with open(TRAIN) as trainData:
	for line in trainData:
		if '|' in line:
		[cur_user,cur_user_rates] = line.strip("\n").split("|")
		trainMod.write(cur_user+"|"+cur_user_rates+"\n")
		else:
		[cur_item,cur_item_rate] = line.strip("\n").split("\t")
		if cur_item in class_lib:
		cur_item_class = class_lib[cur_item]
		else:
		cur_item_class = 1
		trainMod.write(cur_item+"|"+cur_item_rate+"|"+str(cur_item_class)+"\n")


def read_lines(file, num):
	lines = []
	line = file.readline()
	lines.append(line)
	if line:
		for i in range(1,num):
			lines.append(file.readline())
		return lines
	else:
		return line

train_dict = {}
train_user = -1
start_time = time.time()

with open(TEST_1,'w') as testResult:
with open(TEST) as testData:
with open(TRAIN) as trainData:
	lines_test = read_lines(testData,6)
	while lines_test:
		cur_test = lines_test[0].strip("\n").split("|")
		cur_user = cur_test[0]
	while int(train_user) < int(cur_user):
		lines_train = trainData.readline()
		[train_user,train_user_rates] = lines_train.strip("\n").split("|")
		lines_train = read_lines(trainData,int(train_user_rates))
					
	train_dict.clear()
	for line_train in lines_train:
		train_dict_item = line_train.strip("\n").split("\t")
		train_dict[train_dict_item[0]] = train_dict_item[1]
				
	for line_test in lines_test:
		test_song = line_test.strip("\n").split("|")
		testResult.write(cur_user+"|"+test_song[1]+"|")
		del test_song[:2]
		cur_rating = [train_dict[x] if x in train_dict else "none" for x in test_song ]
		testResult.write("|".join(cur_rating))
		testResult.write("\n")
		lines_test = read_lines(testData,6)

def read_lines(f, num):
	lines = []
	line = f.readline().strip("\n").split("\t")
	lines.append(int(line[1]))
	if line:
		for i in range(1,num):
			line = f.readline().strip("\n").split("\t")
			lines.append(int(line[1]))
		return lines
	else:
		return line
		

start_time = time.time()

cur_user = -1
with open(USER_LIST,'w') as userList:
	with open(HIERARCHY) as f:
	for line in f:
		f_list=line.strip("\n").split("|")
	if cur_user != f_list[0]:
		cur_user = f_list[0]
		userList.write(cur_user+"\n")

cur_trainUser = [-1,-1]
with open(USER_MEAN,"w") as trainMeanData:
with open(USER_LIST) as testUserList:
with open(TRAIN) as trainData:
	for line in testUserList:
		cur_user = line.strip("\n")
		while int(cur_trainUser[0])<int(cur_user):
		trainLine = trainData.readline()
		cur_trainUser = trainLine.strip("\n").split("|")
		trainLines = read_lines(trainData,int(cur_trainUser[1]))
		train_sum = 0
	for item in trainLines:
		train_sum += item
		trainMeanData.write(cur_user+"|"+"%.2f"%(train_sum/len(trainLines))+"\n")


RESULT_FILE = "Results/pre.txt"		
TEST_SCORE_FILE = "test_raw_score.txt"		
none_value = int(sys.argv[1])	


if not os.path.isdir("Results"):
	os.makedirs("Results")

threshold=int(sys.argv[2])
sum_1=0.0
cnt_1=0



def sort_list(input_list):
	global threshold
	global sum_1
	global cnt_1
	sorted_list = [[x[0],x[1]+0.5 * x[2]] for x in input_list]
	sorted_list = sorted(sorted_list, key = itemgetter(1))
	pred_dic = {}

	for item in sorted_list:
		if item[1]>threshold:
			pred_dic[item[0]]=1
			sum_1+=1
		else:
			pred_dic[item[0]]=0
		cnt_1+=1
	return 	[pred_dic[item[0]] for item in input_list]


def read_lines(file, num):
	lines = []
	line = file.readline()
	lines.append(line)
	if line:
		for i in range(1,num):
			lines.append(file.readline())
		return lines
	else:
		return line


start_time = time.time()

usermax=0

with open("Data/train_Mean.txt") as f:
	ls=f.readlines()
	user_mean_rating=[0.0]*(38465+1)
	for l in ls:
		lx=l.strip("\n").split("|")
		x=int(lx[0])
		y=float(lx[1])
		user_mean_rating[x]=y	


with open(RESULT_FILE, "w") as predictionFile:
	with open(TEST_SCORE_FILE) as testHierarchy:
	test_list = read_lines(testHierarchy, 6)
	while test_list:
		ori_test_list=test_list
			test_list = [item.strip("\n").strip('\r').split("|")[1:4] for item in test_list]
			user_id=[int(item.strip("\n").strip('\r').split("|")[0]) for item in ori_test_list]
			for i in range(6):
				test_list[i]=[int(item) if item!="none" else none_value for item in test_list[i]]
			prediction_result = sort_list(test_list)
			for item in prediction_result:
				predictionFile.write(str(item)+"\n")
			test_list = read_lines(testHierarchy,6)
